// 管理员首页
const auth = require('../../../utils/auth')
const minLivingAllowanceApi = require('../../../api/minLivingAllowance')
const userApi = require('../../../api/user')
const complaintsApi = require('../../../api/complaints')

Page({
  data: {
    userInfo: {},
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '管理数据加载中...',
    adminStats: {
      pendingCases: 0,
      totalUsers: 0,
      totalNotices: 0,
      totalActivities: 0,
      todayApplications: 0
    },
    feedbackStats: {
      pending: 0,
      today: 0
    },
    quickActions: [
      {
        id: 'cases',
        title: '事项工单处理',
        desc: '对村民提交的事项工单进行处理',
        icon: '⚠️',
        color: '#dc2626',
        count: 0,
        urgent: true
      },
      {
        id: 'activities',
        title: '活动管理',
        desc: '发布和管理村内活动',
        icon: '🎯',
        color: '#f59e0b',
        count: 0
      },
      {
        id: 'users',
        title: '用户管理',
        desc: '管理注册用户信息',
        icon: '👥',
        color: '#2563eb',
        count: 0
      },
      {
        id: 'notices',
        title: '公告管理',
        desc: '发布和管理公告',
        icon: '📢',
        color: '#059669',
        count: 0
      },
      {
        id: 'feedback',
        title: '建议反馈',
        desc: '查看和处理村民建议反馈',
        icon: '💬',
        color: '#2c5530',
        count: 0,
        urgent: false
      },
      {
        id: 'reports',
        title: '数据统计',
        desc: '查看系统使用情况',
        icon: '📊',
        color: '#7c3aed',
        count: 0
      }
    ]
  },

  // 显示全局加载
  showGlobalLoading(text = '管理数据加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad() {
    this.loadUserInfo()
    this.loadAdminStats()
  },

  onShow() {
    this.loadAdminStats()
  },

  // 加载用户信息
  loadUserInfo() {
    const role = auth.getCurrentRole()
    if (!role || role !== 'admin') {
      wx.showToast({
        title: '权限不足',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    // 从本地存储获取用户信息
    const userInfo = wx.getStorageSync('USER_INFO') || {}
    
    const userData = {
      name: userInfo.name || '管理员',
      role: role,
      id: userInfo.accountNumber || 'admin',
      avatar: userInfo.avatar || '',
      province: userInfo.province || '',
      city: userInfo.city || '',
      county: userInfo.county || '',
      village: userInfo.village || '',
      address: userInfo.address || '',
      email: userInfo.email || ''
    }
    
    console.log('管理员页面设置到页面的用户信息:', userData)
    console.log('地理信息显示检查:', {
      province: userData.province,
      city: userData.city,
      county: userData.county,
      village: userData.village,
      hasAnyLocation: !!(userData.province || userData.city || userData.county || userData.village)
    })
    
    this.setData({ userInfo: userData })
  },

  // 加载管理员统计数据
  async loadAdminStats() {
    this.showGlobalLoading('正在加载统计数据...')
    
    try {
      // 并行获取所有统计数据
      const [
        pendingApplicationsResult,
        userCountResult,
        todayApplicationsResult,
        complaintsStatsResult
      ] = await Promise.allSettled([
        // 1. 获取待处理的申请数量
        this.getPendingApplicationsCount(),
        // 2. 获取总用户数量
        userApi.getUserCount(),
        // 3. 获取今日申请数量
        this.getTodayApplicationsCount(),
        // 4. 获取投诉建议统计数据
        complaintsApi.getAdminComplaintStats()
      ])

      // 处理待处理申请数量
      const pendingApplications = pendingApplicationsResult.status === 'fulfilled' 
        ? pendingApplicationsResult.value 
        : 0

      // 处理投诉建议统计数据
      const complaintsStats = complaintsStatsResult.status === 'fulfilled' && complaintsStatsResult.value.success
        ? complaintsStatsResult.value.data
        : { pendingCount: 0 }

      // 计算总待处理事项（申请 + 投诉建议）
      const pendingCases = pendingApplications + (complaintsStats.pendingCount || 0)

      // 处理总用户数量
      const totalUsers = userCountResult.status === 'fulfilled' && userCountResult.value.success
        ? (userCountResult.value.data.totalCount || 0)
        : 0

      // 处理今日申请数量
      const todayApplications = todayApplicationsResult.status === 'fulfilled'
        ? todayApplicationsResult.value
        : 0

      // 更新统计数据
      const adminStats = {
        pendingCases: pendingCases,
        totalUsers: totalUsers,
        totalNotices: 0, // 如果需要可以后续添加公告API
        totalActivities: 0, // 如果需要可以后续添加活动API
        todayApplications: todayApplications
      }

      const feedbackStats = {
        pending: complaintsStats.pendingCount || 0,
        today: 0 // 如果需要可以后续添加今日投诉数量
      }

      this.setData({
        adminStats: adminStats,
        feedbackStats: feedbackStats,
        'quickActions[0].count': pendingCases,
        'quickActions[2].count': totalUsers,
        'quickActions[4].count': todayApplications
      })

      console.log('管理员统计数据加载完成:', adminStats)

    } catch (error) {
      console.error('加载统计数据失败:', error)
      wx.showToast({
        title: '数据加载失败',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.hideGlobalLoading()
    }
  },

  // 获取待处理的申请数量
  async getPendingApplicationsCount() {
    try {
      const result = await minLivingAllowanceApi.getAllApplications({
        status: 'pending',
        page: 1,
        limit: 1
      })
      
      if (result.success && result.data.pagination) {
        return result.data.pagination.total || 0
      }
      return 0
    } catch (error) {
      console.error('获取待处理申请数量失败:', error)
      return 0
    }
  },

  // 获取今日申请数量
  async getTodayApplicationsCount() {
    try {
      // 获取今日的日期字符串（YYYY-MM-DD），使用本地时区
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      const todayStr = `${year}-${month}-${day}`
      
      // 获取今日的申请列表
      const result = await minLivingAllowanceApi.getAllApplications({
        startDate: todayStr,
        endDate: todayStr,
        page: 1,
        limit: 1
      })
      
      if (result.success && result.data.pagination) {
        return result.data.pagination.total || 0
      }
      return 0
    } catch (error) {
      console.error('获取今日申请数量失败:', error)
      return 0
    }
  },


  // 快速操作
  onQuickAction(e) {
    const { action } = e.currentTarget.dataset
    
    switch(action) {
      case 'cases':
        this.navigateToCases()
        break
      case 'activities':
        this.navigateToActivities()
        break
      case 'users':
        this.navigateToUsers()
        break
      case 'notices':
        this.navigateToNotices()
        break
      case 'feedback':
        this.navigateToFeedback()
        break
      case 'reports':
        this.navigateToReports()
        break
    }
  },

  // 跳转到案件管理
  navigateToCases() {
    wx.navigateTo({
      url: '/pages/admin/cases/index',
      success: () => {},
      fail: (err) => {
        wx.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    })
  },

  // 跳转到活动管理
  navigateToActivities() {
    wx.navigateTo({
      url: '/pages/admin/activities/index',
      success: () => {},
      fail: (err) => {
        wx.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    })
  },

  // 跳转到用户管理
  navigateToUsers() {
    wx.navigateTo({
      url: '/pages/admin/users/index',
      success: () => {},
      fail: (err) => {
        wx.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    })
  },

  // 跳转到公告管理
  navigateToNotices() {
    wx.navigateTo({
      url: '/pages/admin/notices/index',
      success: () => {},
      fail: (err) => {
        wx.showToast({ 
          title: '页面跳转失败，请稍后重试', 
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  // 跳转到数据统计
  navigateToReports() {
    wx.navigateTo({
      url: '/pages/admin/stats/index',
      success: () => {},
      fail: (err) => {
        wx.showToast({ 
          title: `页面跳转失败: ${err.errMsg || '未知错误'}`, 
          icon: 'none',
          duration: 3000
        })
      }
    })
  },


  // 跳转到建议反馈管理
  navigateToFeedback() {
    wx.navigateTo({
      url: '/pages/admin/feedback/index',
      success: () => {},
      fail: (err) => {
        wx.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    })
  },


  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadAdminStats()
    wx.stopPullDownRefresh()
  }
})
